package com.welyo.view.quizz {
	import com.welyo.model.QuizzModel;
	import com.welyo.view.quizz.event.QuizzEvent;
	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	/**
	 * ...
	 * @author vu.doan
	 */
	public class CountDownDisplay extends Sprite {
		
		private var timeRemain		:Number;
		private var timer			:Timer;
		
		public function CountDownDisplay() {
			timer = new Timer(1000);
			timer.addEventListener(TimerEvent.TIMER, onTimerHandler);
			
			this.mouseChildren = this.mouseEnabled = false;
			
			QuizzModel.getIntance().addEventListener(QuizzEvent.START_COUNTDOWN, onStartCountDownHandler);
			QuizzModel.getIntance().addEventListener(QuizzEvent.STOP_COUNTDOUWN, onStopCountDownHandler);
		}
		
		public function init():void {
			timeRemain = QuizzModel.getIntance().TotalTime;
		}
		
		public function show():void {
			timeRemain = QuizzModel.getIntance().TimeRemain;
			txtTime.text = timeRemain.toString();
			txtTimeShadow.text = timeRemain.toString();
			visible = true;
		}
		
		public function hide():void {
			visible = false;
		}
		
		private function onStopCountDownHandler(evt:QuizzEvent):void {
			timer.stop();
		}
		
		private function onStartCountDownHandler(evt:QuizzEvent):void {
			timer.start();
		}
		
		private function onTimerHandler(evt:TimerEvent):void {
			timeRemain --;
			if (timeRemain < 0) {
				timeRemain = 0;
				timer.stop();
			} else if (timeRemain == 30) {
				QuizzModel.getIntance().last30();
			}
			QuizzModel.getIntance().TimeRemain = timeRemain;
			txtTime.text = timeRemain.toString();
			txtTimeShadow.text = timeRemain.toString();
		}
	}
}